<template>
	<view class="layout">
		<wd-form ref="form" :model="model">
			<wd-cell-group border>
				<wd-input
					label="分类名"
					label-width="100px"
					prop="name"
					clearable
					v-model="model.name"
					placeholder="请输入分类名"
					:rules="[{
						required: true,
						message: '请填写分类名'
					}]"
				/>
			</wd-cell-group>
			<view class="footer">
				<wd-button
					type="primary"
					size="large"
					@click="handleSubmit"
					block
					:loading="loading"
					:disabled="loading"
				>提交
				</wd-button>
			</view>
		</wd-form>
	</view>

	<wd-notify/>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import typeApi from '../../apis/type';
import {useNotify} from 'wot-design-uni';
import {onLoad} from '@dcloudio/uni-app';

// 消息通知组件
const {
	showNotify
} = useNotify();

const model = reactive({
	name: '',
});

const form = ref();

// 加载状态，默认为false
const loading = ref(false);

const typeId = ref(0);

// 获取分类ID
onLoad((option) => {
	typeId.value = option.id;
})

// 根据分类ID获取分类名
const getTypeInfo = async () => {
	const id = {
		id: typeId.value
	};
	await typeApi.getTypeInfo(id).then((result) => {
		model.name = result.data.name;
	});
}

const handleSubmit = async () => {
	loading.value = true;
	form.value
		// 验证数据格式
		.validate()
		.then(async ({valid}) => {
			// 如果验证通过
			if (valid) {
				// 封装表单数据
				const data = {
					// 提交表单里边必须要有分类ID和分类名
					id: typeId.value,
					name: model.name
				};
				// 发起网络请求提交
				await typeApi.editType(data).then((result) => {
					console.log(result)
					showNotify({
						message: result.msg,
						type: 'success',
						duration: 1500,
						onClosed() {
							// 跳转到分类首页
							uni.navigateTo({
								url: '/pages/type/index'
							})
						}
					});
				});
			}
		})
		// 验证失败时打印日志
		.catch((errors) => {
			console.log(errors, 'error');
		})
		// 最终执行
		.finally(() => {
			loading.value = false;
		})
}

// 页面加载完成后执行获取分类内容方法
onMounted(() => {
	getTypeInfo();
})
</script>

<style scoped lang="scss">
.footer {
	padding: 12px;
}
</style>
